package org.jeecg.modules.demo.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.demo.admin.entity.dto.EmailSentDTO;
import org.jeecg.modules.demo.admin.entity.dto.PaperPutDTO;
import org.jeecg.modules.demo.admin.mapper.adminMapper;
import org.jeecg.modules.demo.admin.service.AdminService;
import org.jeecg.modules.demo.constant.BaseContext;
import org.jeecg.modules.demo.drfAdmin.entity.DrfAdmin;
import org.jeecg.modules.demo.drfAdmin.service.impl.DrfAdminServiceImpl;
import org.jeecg.modules.demo.drfIndividualReview.service.IDrfIndividualReviewService;
import org.jeecg.modules.demo.drfNotice.entity.DrfNotice;
import org.jeecg.modules.demo.drfNotice.service.impl.DrfNoticeServiceImpl;
import org.jeecg.modules.demo.drfReviewAssignments.entity.DrfReviewAssignments;
import org.jeecg.modules.demo.drfReviewAssignments.service.IDrfReviewAssignmentsService;
import org.jeecg.modules.demo.drfStudent.entity.DrfStudent;
import org.jeecg.modules.demo.drfStudent.service.IDrfStudentService;
import org.jeecg.modules.demo.drfTecher.entity.DrfTeacher;
import org.jeecg.modules.demo.drfTecher.service.IDrfTeacherService;
import org.jeecg.modules.demo.drfpapers.entity.DrfPapers;
import org.jeecg.modules.demo.drfpapers.service.IDrfPapersService;
import org.jeecg.modules.demo.drfusers.service.IDrfUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.util.*;

import static org.jeecg.modules.demo.constant.papersStatus.SUBMIT;

@Service
public class AdminServiceImpl extends ServiceImpl<adminMapper, DrfAdmin> implements AdminService {

    @Autowired
    private IDrfPapersService drfPapersService;

    @Autowired
    private IDrfStudentService drfStudentService;

    @Autowired
    private IDrfTeacherService drfTeacherService;

    @Autowired
    private IDrfReviewAssignmentsService drfReviewAssignmentsService;

    @Autowired
    private IDrfIndividualReviewService drfIndividualReviewService;

    @Autowired
    private DynamicMailServiceImpl dynamicMailServiceImpl;

    @Autowired
    private IDrfUsersService drfUsersService;
    @Autowired
    private DrfAdminServiceImpl drfAdminServiceImpl;
    @Autowired
    private DrfNoticeServiceImpl drfNoticeServiceImpl;


    /**
     * 推送论文
     * @param paperPutDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void putPaper(PaperPutDTO paperPutDTO) {
        //输入检查及边界校验
        if (paperPutDTO.getDrfPapersList().isEmpty()) {
            throw new IllegalArgumentException("推送内容不可为空");
        }
        List<DrfReviewAssignments> drfReviewAssignmentsList = new ArrayList<>();
        Set<String> teacherIdsSet = new HashSet<>();
        boolean needAssignTeacher1 = !StringUtils.hasText(paperPutDTO.getTeacherId1());
        boolean needAssignTeacher2 = !StringUtils.hasText(paperPutDTO.getTeacherId2());
        for (DrfPapers paper : paperPutDTO.getDrfPapersList()){
            // 随机选择老师时避免重复
            if (needAssignTeacher1 || needAssignTeacher2) {
                //查询学生
                DrfStudent student = drfStudentService.getByUserId(paper.getStudentId());
                List<DrfTeacher> teachers = drfTeacherService.list(
                        new QueryWrapper<DrfTeacher>().eq("major", student.getMajor())
                );

                if (teachers.size() < 2) {
                    throw new IllegalArgumentException("专业导师不足，无法分配双盲评审");
                }

                List<DrfTeacher> availableTeachers = new ArrayList<>(teachers);

                if (needAssignTeacher1) {
                    DrfTeacher t1 = randomPick(availableTeachers);
                    paperPutDTO.setTeacherId1(t1.getUserId());
                    availableTeachers.remove(t1); // 确保不重复
                }
                if (needAssignTeacher2) {
                    DrfTeacher t2 = randomPick(availableTeachers);
                    paperPutDTO.setTeacherId2(t2.getUserId());
                }
            }
            //记录老师id
            teacherIdsSet.add(paperPutDTO.getTeacherId1());
            teacherIdsSet.add(paperPutDTO.getTeacherId2());
            //拷贝数据到DrfReviewAssignments
            DrfReviewAssignments drfReviewAssignments1 = new DrfReviewAssignments();
            DrfReviewAssignments drfReviewAssignments2 = new DrfReviewAssignments();

            drfReviewAssignments1.setPaperId(paper.getId());
            drfReviewAssignments1.setTeacherId(paperPutDTO.getTeacherId1());
            drfReviewAssignments1.setStatus(SUBMIT);
            drfReviewAssignmentsList.add(drfReviewAssignments1);
            drfReviewAssignments2.setPaperId(paper.getId());
            drfReviewAssignments2.setTeacherId(paperPutDTO.getTeacherId2());
            drfReviewAssignments2.setStatus(SUBMIT);
            drfReviewAssignmentsList.add(drfReviewAssignments2);
        }
        //将数据插入DrfReviewAssignments表
        drfReviewAssignmentsService.saveBatch(drfReviewAssignmentsList);
        //依据老师idset获取老师信息
        List<DrfTeacher> teachers = drfTeacherService.listByIds(teacherIdsSet);
        //获取老师信息并封装成DTO
        List<EmailSentDTO>  emailSentDTOS = new ArrayList<>();
        for (DrfTeacher teacher : teachers) {
            EmailSentDTO emailSentDTO = new EmailSentDTO();
            emailSentDTO.setEmail(teacher.getEmail());
            emailSentDTO.setUserId(teacher.getUserId());
            //依据老师userId查询User表
            emailSentDTO.setPassword(drfUsersService.getById(teacher.getUserId()).getPassword());
        }
        sentEmail(emailSentDTOS);
    }

    /**
     * 随机选择老师
     * @param list
     * @return
     */
    private DrfTeacher randomPick(List<DrfTeacher> list) {
        return list.get((int)(Math.random() * list.size()));
    }


    /**
     * 发送邮件
     * @param emailSentDTOS
     */
    private void sentEmail(List<EmailSentDTO>  emailSentDTOS) {
        //获取当前登录人员的id
        Long userId = BaseContext.getCurrentId(); // 直接拿到 ID
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        for (EmailSentDTO emailSentDTO : emailSentDTOS) {
            dynamicMailServiceImpl.sendMail(emailSentDTO, true);
        }
    }


    /**
     * 发送公告
     * @param title
     * @param content
     * @param startTime
     * @param ambit
     * @return
     */
    @Override
    public void sendNotice(String title , String content, Date startTime, Integer ambit){
        DrfNotice drfNotice = new DrfNotice();
        drfNotice.setTitle(title);
        drfNotice.setContent(content);
        drfNotice.setStartTime(startTime);
        drfNotice.setAmbit(ambit);
        drfNoticeServiceImpl.save(drfNotice);
    }

}

